package com.infocollect.project.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infocollect.common.utils.ServletUtils;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.framework.security.service.TokenService;
import com.infocollect.project.api.entity.*;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.JSONUtil;
import com.infocollect.project.api.mapper.*;
import com.infocollect.project.api.req.QueryPorcessInsListReq;
import com.infocollect.project.api.service.*;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.form.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infocollect.project.api.entity.*;
import com.infocollect.project.api.mapper.TappPorcessinsMapper;
import com.infocollect.project.api.service.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (TappPorcessins)表服务实现类
 *
 * @author makejava
 * @since 2019-12-25 10:32:29
 */
@Service("tappPorcessinsService")
public class TappPorcessinsServiceImpl  extends ServiceImpl<TappPorcessinsMapper, TappPorcessinsEntity> implements ITappPorcessinsService {
    @Autowired
    private TokenService tokenService;
    @Resource
    private ITappProcessChartService tappProcesschartDao;

    @Resource
    private ITappActinsService tappActinsDao;
    @Resource
    private ITappFromService tappFromDao;
    @Resource
    private ITappFromDataService tappFromdataDao;
    @Resource
    private ITappActinsCommunicateService tappActinscommunicatedao;

    @Resource
    private ITappProcessService tappProcessDao;
    /**
     * 通过ID查询单条数据
     *
     * @param fid 主键
     * @return 实例对象
     */
    @Override
    public TappPorcessinsEntity queryById(Long fid) {
        return this.baseMapper.queryById(fid);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<TappPorcessinsEntity> queryAllByLimit(int offset, int limit) {
        return this.baseMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param tappPorcessins 实例对象
     * @return 实例对象
     */
    @Override
    public TappPorcessinsEntity insert(TappPorcessinsEntity tappPorcessins) {
        this.baseMapper.insert(tappPorcessins);
        return tappPorcessins;
    }

    /**
     * 修改数据
     *
     * @param tappPorcessins 实例对象
     * @return 实例对象
     */
    @Override
    public TappPorcessinsEntity update(TappPorcessinsEntity tappPorcessins) {
        this.baseMapper.updateById(tappPorcessins);
        return this.queryById(tappPorcessins.getFid());
    }

    /**
     * 通过主键删除数据
     *
     * @param fid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long fid) {
        return this.baseMapper.deleteById(fid) > 0;
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     * @menu 根据实体对象是否有值 进行查询
     */
    @Override
    public List<TappPorcessinsEntity> queryAll(TappPorcessinsEntity entity) {
        return this.baseMapper.queryAll(entity);
    }

    /**
     * 获取流程发起页面信息
     *
     * @param processid
     * @param processinsid
     * @param actinsid
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject GetProcessFromInfo(Long processid, Long processinsid, Long actinsid, String UserName, String viewmodel) throws Exception {
        ///进入页面的场景有 我的待办 我的已办已阅 我的发起 查看
        ////进入该页面有如下几种场景  发起流程，我的待办，申请人查看流程，审批人查看流程，抄送人查看，沟通人查看 其他方式查看
        ////发起流程 processid！=null processinsid==null actinsid==null 获取发起的节点权限
        ////我的待办 processid！=null processinsid!=null actinsid!=null viewmodel==todo 并且当前节点的审批人是 当前用户，并且状态为未处理  包含沟通 抄送 参数必须传入 获取节点权限
        ////申请人查看流程 processid！=null processinsid!=null  actinsid!=null viewmodel==start 当前用户等于发起人或申请人 参数必须传入 获取发起的节点权限
        // 审批人查看流程  processid！=null processinsid!=null  actinsid!=null viewmodel=read 只要求传入 processinsid 获取节点权限
        // processid！=null processinsid!=null   viewmodel=其它 并且对应抄送表中抄送人等于当前用户，数据权限默认设置为默认
        TappProcessChartEntity processchart = this.tappProcesschartDao.queryByProcessId(processid);
        if(processchart==null){
            throw new Exception("未找到流程配置信息！");
        }
        JSONObject resultJson = new JSONObject();
        JSONObject json = JSONObject.fromObject(processchart.getFlowdata());
        TappFromEntity from = tappFromDao.queryById(json.getLong("FromID"));
        resultJson.put("head", json.getJSONObject("Head"));
        resultJson.put("flowname", json.getString("FlowName"));
        resultJson.put("BusinessModuleID", json.optString("BusinessModuleID"));
        resultJson.put("BusinessMoudle", json.optString("BusinessMoudle"));
        resultJson.put("FlowTempContext", from.getFromcontent());
        List<TappActinsEntity> tappActinsEntityList=  tappActinsDao.getCompletedNodeList(processinsid);
        List<String> actchartidList=new ArrayList<>();
        if(tappActinsEntityList!=null){
        actchartidList=   tappActinsEntityList.stream().map(TappActinsEntity::getFactchartid).collect(Collectors.toList());
        }
        resultJson.put("actchartids", actchartidList);
        String actChartId = "F_Start";
        String flowstatusName="";
        Integer flowstatus=0;
        resultJson.put("operateType",viewmodel);
        if (viewmodel!=null&&viewmodel.equals("todo")) { //我的待办待阅进入
            if ((processinsid==null||processinsid == 0) || (actinsid==null||actinsid == 0)) {
                throw new Exception("传输参数错误！");
            }
            TappActinsEntity tappActins = tappActinsDao.queryById(actinsid);
            if (tappActins == null) {
                throw new Exception("传输参数错误！");
            }
            TappPorcessinsEntity tappPorcessins= baseMapper.queryById(processinsid);
            if(tappPorcessins==null){
                throw new Exception("传输参数错误！");
            }
            flowstatusName=tappPorcessins.getFcurrentactname();
            flowstatus=tappPorcessins.getFstatus();
            actChartId=tappActins.getFactchartid();
            ///tappActins.getFstatus()=0 流程正在沟通 等于1正常审批界面
            if (tappActins.getFapproversuser().equals(UserName) && (tappActins.getFstatus() == 1||tappActins.getFstatus() == 0)) {
                actChartId = tappActins.getFactchartid();
                JSONObject currentNodeJson = json.getJSONObject("Node").getJSONObject(actChartId);
                resultJson.put("OperatePermission", JSONUtil.objToJson(currentNodeJson.get("OperatePermission")));
                resultJson.put("AttachmentPermission", JSONUtil.objToJson(currentNodeJson.get("AttachmentPermission")));
                resultJson.put("DataPermission", JSONUtil.objToJson(currentNodeJson.get("DataPermission")));
                resultJson.put("IsRead", tappActins.getFstatus() == 0);
                resultJson.put("actid", tappActins.getFactid());
                if(tappActins.getFstatus() == 0){
                    resultJson.put("operateType", "quxiaogoutong");
                }else{
                    if(tappActins.getFopendate()!=null) {
                        tappActins.setFopendate(new Date());
                        tappActinsDao.updateById(tappActins);
                    }
                }
                resultJson.put("FromData",tappFromdataDao.queryById(tappPorcessins.getFromdataid()).getFromdata());
            }   else {
              List<TappActinsCommunicateEntity>  tappActinscommunicateList= tappActinscommunicatedao.queryTodoCommunicate(UserName,actinsid,processinsid);
                if(!tappActinscommunicateList.isEmpty()&&tappActinscommunicateList.size()>0){
                    actChartId = tappActins.getFactchartid();
                    JSONObject currentNodeJson = json.getJSONObject("Node").getJSONObject(actChartId);
                    resultJson.put("OperatePermission","[]");
                    resultJson.put("AttachmentPermission", JSONUtil.objToJson(currentNodeJson.get("AttachmentPermission")));
                    resultJson.put("DataPermission", JSONUtil.objToJson(currentNodeJson.get("DataPermission")));
                    resultJson.put("actid", tappActins.getFactid());
                    resultJson.put("FromData",tappFromdataDao.queryById(tappPorcessins.getFromdataid()).getFromdata());
                    for (TappActinsCommunicateEntity item:tappActinscommunicateList) {
                        if(item.getFcommunicatetype().equals(5)){ ///沟通
                            item.setFopendate(new Date());
                            resultJson.put("IsRead", true);
                            resultJson.put("operateType", "goutong");
                        }
                        if(item.getFcommunicatetype().equals(6)){
                            item.setFopendate(new Date());
                            item.setFcompleteddate(new Date());
                            item.setFstatus(2);
                            resultJson.put("IsRead", true);
                            resultJson.put("operateType", "CC");
                        }
                        tappActinscommunicatedao.updateById(item);
                    }
                }else {
                    ///这里需要判断当前节点是否有抄送和沟通  如果都不是 就是非法进入
                    throw new Exception("非法进入！");
                }
            }
        }
        else if (viewmodel!=null&&viewmodel.equals("read")) { //我的已办已阅进入
            if ((processinsid==null||processinsid == 0) || (actinsid==null||actinsid == 0)) {
                throw new Exception("传输参数错误！");
            }
            TappActinsEntity tappActins = tappActinsDao.queryById(actinsid);
            if (tappActins == null) {
                throw new Exception("传输参数错误！");
            }
            TappPorcessinsEntity tappPorcessins= baseMapper.queryById(processinsid);
            if(tappPorcessins==null){
                throw new Exception("传输参数错误！");
            }
            flowstatusName=tappPorcessins.getFcurrentactname();
            flowstatus=tappPorcessins.getFstatus();
            actChartId = tappActins.getFactchartid();
            JSONObject currentNodeJson = json.getJSONObject("Node").getJSONObject(actChartId);
            resultJson.put("OperatePermission", JSONUtil.objToJson(currentNodeJson.get("OperatePermission")));
            resultJson.put("AttachmentPermission", JSONUtil.objToJson(currentNodeJson.get("AttachmentPermission")));
            resultJson.put("DataPermission", JSONUtil.objToJson(currentNodeJson.get("DataPermission")));
            resultJson.put("IsRead", true);
            resultJson.put("actid", tappActins.getFactid());
            resultJson.put("FromData",tappFromdataDao.queryById(tappPorcessins.getFromdataid()).getFromdata());
        }
        else if (viewmodel!=null&&viewmodel.equals("start")) { ///从我的发起进入 主要是控制是否需要撤销废弃
            if ((processinsid==null||processinsid == 0) ) {
                throw new Exception("传输参数错误！");
            }
           TappPorcessinsEntity tappPorcessins= baseMapper.queryById(processinsid);
            if(tappPorcessins==null){
                throw new Exception("传输参数错误！");
            }
            flowstatusName=tappPorcessins.getFcurrentactname();
            flowstatus=tappPorcessins.getFstatus();
            ///判断发起人跟当前用户是否一致 如果不一致 代表非法进入
            if(!tappPorcessins.getFstarter().equals(UserName)){
                throw new Exception("非法进入！");
            }
            resultJson.put("IsRead", true);
            if(actinsid!=null&&actinsid!=0){
                TappActinsEntity tappActins = tappActinsDao.queryById(actinsid);
                if (tappActins != null) {
                    actChartId = tappActins.getFactchartid();
                }
            }else{
                TappActinsEntity tappActins =   tappActinsDao.queryTodoActins(processinsid);
                if (tappActins != null) {
                    actChartId = tappActins.getFactchartid();
                }
            }
            JSONObject currentNodeJson = json.getJSONObject("Node").getJSONObject(actChartId);

            resultJson.put("OperatePermission", JSONUtil.objToJson(currentNodeJson.get("OperatePermission")));
            resultJson.put("AttachmentPermission", JSONUtil.objToJson(currentNodeJson.get("AttachmentPermission")));
            resultJson.put("DataPermission", JSONUtil.objToJson(currentNodeJson.get("DataPermission")));
            resultJson.put("actid", currentNodeJson.getLong("atctid"));
            resultJson.put("FromData",tappFromdataDao.queryById(tappPorcessins.getFromdataid()).getFromdata());
        }
        else if (viewmodel!=null&&viewmodel.equals("draft")) {
            if ((processinsid==null||processinsid == 0) ) {
                throw new Exception("传输参数错误！");
            }
            TappPorcessinsEntity tappPorcessins= baseMapper.queryById(processinsid);
            if(tappPorcessins==null){
                throw new Exception("传输参数错误！");
            }
            flowstatusName=tappPorcessins.getFcurrentactname();
            flowstatus=tappPorcessins.getFstatus();
            ///判断发起人跟当前用户是否一致 如果不一致 代表非法进入
            if(!tappPorcessins.getFstarter().equals(UserName)){
                throw new Exception("非法进入！");
            }
            if(tappPorcessins.getFstatus().equals(0)) {
                resultJson.put("IsRead", true);
            }else{
                resultJson.put("IsRead", false);
            }
            JSONObject currentNodeJson = json.getJSONObject("Node").getJSONObject(actChartId);
            resultJson.put("OperatePermission", JSONUtil.objToJson(currentNodeJson.get("OperatePermission")));
            resultJson.put("AttachmentPermission", JSONUtil.objToJson(currentNodeJson.get("AttachmentPermission")));
            resultJson.put("DataPermission", JSONUtil.objToJson(currentNodeJson.get("DataPermission")));
            resultJson.put("actid", currentNodeJson.getLong("atctid"));
            resultJson.put("FromData",tappFromdataDao.queryById(tappPorcessins.getFromdataid()).getFromdata());
        }
        else {
            if ((processinsid==null||processinsid == 0) && (actinsid==null||actinsid == 0) && (viewmodel==null||viewmodel.equals(""))) { ///发起的入口
                JSONObject currentNodeJson = json.getJSONObject("Node").getJSONObject(actChartId);
                resultJson.put("OperatePermission", JSONUtil.objToJson(currentNodeJson.get("OperatePermission")));
                resultJson.put("AttachmentPermission", JSONUtil.objToJson(currentNodeJson.get("AttachmentPermission")));
                resultJson.put("DataPermission", JSONUtil.objToJson(currentNodeJson.get("DataPermission")));
                resultJson.put("IsRead", false);
                resultJson.put("actid", currentNodeJson.getLong("atctid"));
                resultJson.put("FromData","{}");
                resultJson.put("operateType", "faqi");
            } else {  ///其他入口  如果不给需要判断有没有权限 查看 后期再加
                resultJson.put("IsRead", true);
                resultJson.put("OperatePermission", "[]");
                resultJson.put("AttachmentPermission", "[]");
                resultJson.put("DataPermission", "[]");
                resultJson.put("actid",0);
                if(processid!=null&&processinsid != 0) {
                    TappPorcessinsEntity tappPorcessins= baseMapper.queryById(processinsid);
                    if(tappPorcessins==null){
                        throw new Exception("传输参数错误！");
                    }
                    flowstatus=tappPorcessins.getFstatus();
                    flowstatusName= tappPorcessins.getFcurrentactname();
                    resultJson.put("FromData", tappFromdataDao.queryById(tappPorcessins.getFromdataid()).getFromdata());
                }else{
                        throw new Exception("传输参数错误！");
                }
            }
        }
        resultJson.put("currentChartId",actChartId);
        resultJson.put("flowstatus", flowstatus);
        resultJson.put("flowstatusName", flowstatusName==null?"":flowstatusName);
        return resultJson;
    }
    @Override
    public R<List<TappPorcessinsEntity>> queryporcessinsList(QueryPorcessInsListReq param){

        try {
            QueryPorcessinsEntity porcessins = new QueryPorcessinsEntity();
            porcessins.setActName(param.getActName());
            if(param.getApprovingUser()!=null) {
                porcessins.setApprovingUser(param.getApprovingUser().getNo());
            }
            if(param.getFapplicantuser()!=null) {
                porcessins.setFapplicantuser(param.getFapplicantuser().getNo());
            }
            porcessins.setFprocinsname(param.getFprocinsname());
            porcessins.setFprocinsno(param.getFprocinsno());
            if(param.getFstarttime()!=null&&param.getFstarttime().size()>0) {
                porcessins.setFstarttimeStart(param.getFstarttime().get(0));
                porcessins.setFstarttimeEnd(param.getFstarttime().get(1));
            }
            if(param.getStartUser()!=null) {
                porcessins.setStartUser(param.getStartUser().getNo());
            }
            porcessins.setProcInsState(param.getProcInsState());
            LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
            porcessins.setUsername(currentUserInfo.getUserName());
//            porcessins.set(param.getActName());
//            MapHelper.setObjectValue(porcessins, param);
            int page =param.getPage();
            int rows = param.getRows();
            PageHelper.startPage(page, rows);
            String viewstate=param.getViewState()==null||"".equals(param.getViewState()) ?"1":param.getViewState();
//            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            porcessins.setUsername(currentUserInfo.getUserName());
            List<TappPorcessinsEntity> list=null;
            switch (viewstate){
                case "1": list=baseMapper.MyAllPorcessinsList(porcessins);break;
                case "2":list=baseMapper.MyDraftPorcessinsList(porcessins);break;
                case "3":list=baseMapper.MyStartPorcessinsList(porcessins);

                break;
                case "4":list=baseMapper.MyToDoPorcessinsList(porcessins);break;
                case "5":list=baseMapper.MyReadporcessinsList(porcessins);break;
                default:list=baseMapper.MyAllPorcessinsList(porcessins);break;
            }
            for (TappPorcessinsEntity item:list) {
                if(item.getFstatus()==2||item.getFstatus()==7) {
                    TappActinsEntity tappActins=   tappActinsDao.queryTodoActins(item.getFid());
                    if(tappActins!=null){
                        item.setActinsid(tappActins.getFid().toString());
                    }
                }
                TappProcessEntity tappProcess=  tappProcessDao.queryById(item.getFprocessid());
                if(tappProcess!=null){
                    item.setProcname(tappProcess.getFprocessname());
                }
            }
            PageInfo pageInfo = new PageInfo(list);
            return R.newOk(list,(int)pageInfo.getTotal());
        }catch (Exception ex){
            return R.newError(ex.getMessage());

        }

   }

}
